package com.sdleyou.treepro.business.api.pay;

import com.sdleyou.treepro.common.service.OrderManager;
import com.sdleyou.treepro.system.payment.HttpKit;
import com.sdleyou.treepro.system.payment.PaymentKit;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/pay/")
public class PayCallBackController {

    /**
     * 成功的标识
     */
    private final static String SUCCESS="SUCCESS";

    /**
     * 返回状态码的变量名
     *
     */
    private final static String RETURN_CODE="return_code";

    @Autowired
    private OrderManager orderManager;

    /**
     * 功能描述: <小程序回调>
     **/
    @RequestMapping("/wxProPayNotify")
    public void wxProPayNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //System.out.println("进入微信小程序支付回调");
        String xmlMsg = HttpKit.readData(request);
        //System.out.println("微信小程序通知信息"+xmlMsg);
        Map<String, String> resultMap = PaymentKit.xmlToMap(xmlMsg);
        //System.out.println("微信小程序通知信息"+resultMap.toString());
        if(resultMap.get(RETURN_CODE).equals(SUCCESS)){
            String orderNo = resultMap.get("out_trade_no");
            //System.out.println("微信小程序支付成功,订单号{}" + orderNo);
            if(!TextUtils.isEmpty(orderNo)) {
                orderManager.updateOrderStatus(orderNo);
            }
        }
        String result =  "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        try {
            response.getWriter().write(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}